<template>
  <Picker :visible="visible" class="contact-picker">
    <StatusHandle key="statusHandle" ref="statusHandle" :get="getData">
      <div>
        <!-- <div class="sel" @click="selectVisibles">
          <van-icon name="search" />
          <input :disabled="true" placeholder="请输入搜索关键词" />
        </div> -->
        <van-search
            readonly
            placeholder="请输入搜索关键词"
             @click="selectVisibles"
          />
        <div class="closePicker" @click="closePicker">关闭</div>
        <div class="navigation">
          <div
            :class="index === level ? 'level' : ''"
            v-for="(item, index) in navigation"
            :key="index"
            @click="navigate(item, index)"
          >
            {{ item.departName }}
            <span v-if="index + 1 < navigation.length">></span>
          </div>
        </div>

        <div v-if="currentLevelDatasource.length" class="list">
          <!-- 判断当前页面有没有用户 有则可以全选 -->
          <div style="margin: 15px" v-if="isAllSelect">
            <van-checkbox :value="isCurrentLevelAllSelected" @click="toggleAll"
              >全选
            </van-checkbox>
          </div>
          <van-checkbox-group ref="checkboxGroupresult" :value="selectedIdList">
            <van-cell-group>
              <van-cell
                v-for="item in currentLevelDatasource"
                :key="item.id"
                clickable
                :title="
                  +item.type === TYPE.DEPART
                    ? `${item.departName}(${item.members || 0}人)`
                    : ''
                "
                @click="toggle(item)"
              >
                <template #icon>
                  <van-checkbox
                    :name="item.id"
                    v-if="item.type === type"
                    ref="checkboxes"
                    style="margin-right: 10px"
                  />
                  <van-checkbox
                    :name="item.id"
                    v-model="item.checked"
                    v-else
                    ref="checkboxes"
                    style="margin-right: 10px"
                  />
                  <div v-if="+item.type === TYPE.USER">
                    <img
                      class="avatar"
                      v-if="item.avatar"
                      :src="item.avatar"
                      alt=""
                    />
                    <div class="avatar" v-else>
                      {{ item.realname.slice(item.realname.length - 2 || "") }}
                    </div>
                  </div>
                  <div v-if="+item.type === TYPE.USER" class="avatar-title">
                    {{ item.realname }}
                  </div>
                </template>
                <template #right-icon v-if="item.type === TYPE.DEPART">
                  <span
                    :class="
                      selectedIdList.includes(item.id)
                        ? 'disabled'
                        : 'can-click'
                    "
                    @click.stop="goNextLevel(item)"
                  >
                    <van-icon name="cluster-o" />
                    下级
                  </span>
                </template>
              </van-cell>
            </van-cell-group>
          </van-checkbox-group>
        </div>
        <div v-else class="nodata">
          <div>
            <van-icon name="contact" size="30" />
            <p>暂无数据</p>
          </div>
        </div>
        <div class="footer">
          <div @click="selectedVisible = true">
            {{ title.num }}
            <van-icon name="arrow-up" />
          </div>
          <div>
            <div class="btn" @click="confirm">确定</div>
          </div>
        </div>
      </div>
    </StatusHandle>
    <div v-if="selectedVisible" class="selected-list">
      <div class="head">
        <p class="flex-row align">
          <span>{{ title.all }}</span>
          <span class="selected-edit" @click="selectedEdit">确定</span>
        </p>
      </div>
      <div class="sel-list">
        <div v-for="item in selectedList" :key="item.id" class="selected-item">
          <span v-if="item.type === TYPE.DEPART">
            {{ item.departName }}({{ item.members || 0 }}人)
          </span>
          <span v-else style="display: flex; align-items: center">
            <img class="avatar" v-if="item.avatar" :src="item.avatar" alt="" />
            <div class="avatar" v-else>
              {{ item.realname.slice(item.realname.length - 2 || 0) }}
            </div>
            <div>
              {{ item.realname }}
            </div>
          </span>
          <van-icon name="close" size="20" @click="toggle(item)" />
        </div>
      </div>
    </div>
    <div class="select-list" v-if="selectVisible">
      <form action="/">
        <van-search
          v-model="searchValue"
          show-action
          placeholder="请输入搜索关键词"
          @input="onSearch"
          @search="onSearch"
          :clearable="false"
          @cancel="selectVisible = false"
        />
      </form>
      <div class="sel-list">
        <van-checkbox-group :value="selectedIdList">
          <div v-if="searchResultList.length < 1" class="nodata">
            <van-icon name="contact" size="30" />
            <p>暂无数据</p>
          </div>
          <van-cell-group v-else style="margin-bottom:0.45rem">
            <van-cell
              v-for="item in searchResultList"
              clickable
              :key="item.id"
              :title="``"
              @click="toggle(item)"
            >
              <template #icon>
                <van-checkbox :name="item.id" @click.stop />
                <div v-if="item.type === TYPE.USER" style="display: flex">
                  <img
                    style="margin: 0px 10px"
                    class="avatar"
                    v-if="item.avatar"
                    :src="item.avatar"
                    alt=""
                  />
                  <div class="avatar" style="margin: 0px 10px" v-else>
                    {{ item.realname.slice(item.realname.length - 2 || 0) }}
                  </div>
                  <div class="avatar-title">
                    {{ item.realname }}
                  </div>
                </div>
                <div v-else style="margin: 0px 10px">
                  {{ item.departName }}({{ item.members || 0 }}人)
                </div>
              </template>
            </van-cell>
            <div v-if="searchResultList.length > 12" class="footer-cell">
              <div class="footer">
                <div @click="selectedVisible = true">
                  {{ title.num }}
                  <van-icon name="arrow-up" />
                </div>
                <div>
                  <div class="btn" @click="confirm">确定</div>
                </div>
              </div>
            </div>
            <div v-else class="footer-cell-boot">
              <div class="footer">
                <div @click="selectedVisible = true">
                  {{ title.num }}
                  <van-icon name="arrow-up" />
                </div>
                <div>
                  <div class="btn" @click="confirm">确定</div>
                </div>
              </div>
            </div>
          </van-cell-group>
        </van-checkbox-group>
        <!-- <div v-for="item in searchResultList" :key="item.id">
          {{ item.realname }}
        </div> -->
      </div>
    </div>
  </Picker>
</template>

<script>
import { getAction } from "@/api/manage";
import Picker from "./picker";
import { Tip } from "./utils";
import StatusHandle from "./StatusHandle";
import dataSource from "./dataSource";

const API = {
  ALL_USER_LIST() {
    return getAction("/sys/user/selectlist/notdel").then((res) => {
      return res.result.map((item) => {
        const { id, realname } = item;
        return {
          ...item,
          type: TYPE.USER,
          label: realname,
          value: id,
        };
      });
    });
  },
  ALL_DEPART_LIST(params) {
    return getAction("/sys/sysDepart/page", params).then((res) => {
      return res.result.map((item) => {
        const { id, departName } = item;
        return {
          ...item,
          type: TYPE.DEPART,
          label: departName,
          value: id,
        };
      });
    });
  },
  CONFIG() {
    return getAction("/sys/user/selectlist/notdel");
  },

  USER_LIST(data, Config) {
    return getAction("/sys/user/list", data, Config);
  },
  LIST(data, Config) {
    return getAction("/sys/sysDepart/getDepartAndUserByDepartId", data, Config);
  },

  LISTS(data, Config) {
    return getAction("/sys/user/queryUserByDepId", data, Config);
  },
};
export const TYPE = {
  DEPART: 2,
  USER: 1,
};

export default {
  components: { Picker, StatusHandle },
  name: "ContactPicker",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    visible: Boolean,
    value: {
      type: String,
    },
    max: [Number],
    type: {
      type: [String, Number],
      default: TYPE.USER,
    },
    approvedby: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      allSelectState: false,
      //是否完成value数据的回显初始化
      init: false,
      TYPE,
      selectVisible: false,
      isAllSelect: false,
      searchResultList: [],
      navigation: [
        {
          id: "",
          departName: "通讯录",
        },
      ],
      level: 0,
      currentLevelDatasource: [],
      selectedList: [],
      selectedVisible: false,
      searchValue: "",
    };
  },
  created() {},
  computed: {
    //选中的id列表
    selectedIdList() {
      return this.selectedList.map((item) => item.id);
    },
    isCurrentLevelAllSelected() {
      const { currentLevelDatasource, selectedIdList, type } = this;
      return currentLevelDatasource
        .filter((item) => +item.type === type)
        .every((item) => {
          return !!selectedIdList.includes(item.id);
        });
    },
    title() {
      const { type, selectedList } = this;
      if (type === TYPE.USER) {
        return {
          all: "已选联系人",
          num: `已经选择${selectedList.length}人`,
        };
      } else {
        return {
          all: "已选部门",
          num: `已经选择${selectedList.length}个部门`,
        };
      }
    },
  },
  watch: {
    visible(v) {
      if (!v) {
        this.selectedVisible = v
      }
    }
  },
  methods: {
    selectVisibles() {
      if (this.approvedby.length > 0) {
        this.$toast("请在指定人员内选择人员");
      } else {
        this.selectVisible = true;
      }
    },
    onSearch(v) {
      if (this.type === TYPE.USER) {
        const obj = {
          pageNo: 1,
          pageSize: 100000,
          departId: "",
          realname: `*${v}*`,
        };
        API.USER_LIST(obj)
          .then((res) => {
            this.$nextTick(() => {
              this.searchResultList = res.result.records.map((item) => {
              const { id, departName } = item;
              return {
                ...item,
                type: TYPE.USER,
              };
            });
            })
          })
          .catch((res) => {});
      } else {
        API.ALL_DEPART_LIST({
          departName: v,
        }).then((res) => {
          this.searchResultList = res.result.map((item) => {
            const { id, departName } = item;
            return {
              ...item,
              type: TYPE.DEPART,
            };
          });
        });
      }
    },
    confirm() {
      const { selectedIdList } = this;
      this.$emit("confirm", selectedIdList.join(","), this.selectedList);
    },
    selectedEdit() {
      this.selectedVisible = false;
    },
    closePicker() {
      this.$emit("closePicker");
    },
    toggleAll(v) {
      const {
        isCurrentLevelAllSelected,
        currentLevelDatasource,
        selectedList,
        selectedIdList,
        max,
        type,
      } = this;
      const currentLevelIdDatasource = currentLevelDatasource.map(
        (item) => item.id
      );

      if (isCurrentLevelAllSelected) {
        //如果是已经全选了 就删除 挨个删
        const next = selectedList.filter((item) => {
          return !currentLevelIdDatasource.includes(item.id);
        });
        this.selectedList = next;
      } else {
        const addList = [];
        currentLevelDatasource
          .filter((item) => +item.type === type)
          .forEach((item) => {
            if (!selectedIdList.includes(item.id)) {
              addList.push(item);
            }
          });
        if (selectedList.length + addList.length > max) {
          return Tip.error(`最多选中${max}项`);
        }

        const next = selectedList.concat(addList);
        this.selectedList = next;
        // this.selectedList.push()
      }
    },
    getAll() {
      let info = {
        key: "user",
        call: API.ALL_USER_LIST,
      };
      if (this.type === TYPE.DEPART) {
        info = {
          key: "depart",
          call: API.ALL_DEPART_LIST,
        };
      }
      const cache = dataSource.get(info.key);
      if (cache) {
        return Promise.resolve(cache);
      }
      return info.call().then((all) => {
        dataSource.set(info.key, all);
        return all;
      });
    },
    getData(parent) {
      console.log();
      const { value, init, type } = this;
      const initList = String(value || "").split(",");
      console.log(initList, "initList--ww");
      if (initList.length && !init) {
        return this.getAll().then((config) => {
          this.init = true;
          this.selectedList = initList
            .map((value) => {
              return config.find((item) => item.value === value);
            })
            .filter((n) => !!n);
          console.log(this.selectedList, config, initList, "config-ww");
          return this.getList(parent);
        });
      } else {
        return this.getList(parent);
      }
    },
    getList(parent) {
      // return API.LIST({ id: parent || '', status: 1 }).then(res => {
      //   const { departs, sysUsers } = res
      //   if (this.type === TYPE.DEPART) {
      //     this.isAllSelect = departs.length > 0 ? true : false
      //     this.currentLevelDatasource = departs
      //   } else {
      //     this.isAllSelect = sysUsers.length > 0 ? true : false
      //     this.currentLevelDatasource = departs.concat(sysUsers)
      //   }
      // })

      this.selectedList = [];
      return API.LIST({ id: parent, status: 1 }).then((res) => {
        const { departs, sysUsers } = res.result;
        if (this.approvedby.length > 0) {
          console.log(this.approvedby);
          this.isAllSelect = this.approvedby.length > 0 ? true : false;
          this.approvedby.forEach((value, index) => {
            value["type"] = "1";
          });
          this.currentLevelDatasource = this.approvedby;
        } else {
          if (this.type === TYPE.DEPART) {
            this.isAllSelect = departs.length > 0 ? true : false;
            this.currentLevelDatasource = departs;
            this.currentLevelDatasource.forEach((value, index) => {
              value["checked"] = false;
            });
          } else {
            this.isAllSelect = sysUsers.length > 0 ? true : false;
            this.currentLevelDatasource = departs.concat(sysUsers);
            this.currentLevelDatasource.forEach((value, index) => {
              value["checked"] = false;
            });
          }
        }
      });
    },
    navigate(item, index) {
      if (index === this.level) {
        return;
      }
      this.level = index;
      this.navigation.length = index + 1;
      this.$refs.statusHandle.refresh(item.id);
    },
    goNextLevel(item) {
      if (this.selectedIdList.includes(item.id)) {
        return;
      }
      //面包屑导航增加菜单
      this.navigation.push(item);
      this.level = this.navigation.length - 1;
      this.$refs.statusHandle.refresh(item.id);
    },
    toggle(item) {
      console.log(item);
      const { max, selectedList, type } = this;
      // if (+item.type === TYPE.DEPART && type === TYPE.USER) {
      //   return this.goNextLevel(item);
      // }
      if (+item.type === TYPE.DEPART && type === TYPE.USER) {
        return API.LISTS({ id: item.id || "", status: 1 }).then((res) => {
          var sysUsers = res.result;
          sysUsers.forEach((value, index) => {
            value["type"] = "1";
          });
          console.log(res);
          const { selectedList, selectedIdList, max, type } = this;
          var currentLevelDatasource = sysUsers;
          const addList = [];
          currentLevelDatasource
            .filter((item) => +item.type === type)
            .forEach((item) => {
              if (!selectedIdList.includes(item.id)) {
                addList.push(item);
              }
            });
          if (selectedList.length + addList.length > max) {
            return Tip.error(`最多选中${max}项`);
          }

          const next = selectedList.concat(addList);
          this.selectedList = next;
          // this.currentLevelDatasource[index].checked = true
        });
      }
      if (+item.type === TYPE.USER && type === TYPE.DEPART) {
        return;
      }
      const next = [...selectedList];
      const index = next.findIndex((i) => {
        return i.id === item.id;
      });
      //存在则删除
      if (index > -1) {
        next.splice(index, 1);
      } else {
        if (typeof max === "number" && selectedList.length >= max) {
          return Tip.error(`最多选中${max}项`);
        } else {
          next.push(item);
        }
      }
      this.selectedList = next;
    },
  },
};
</script>
<style lang='scss' scoped>
.avatar {
  justify-content: center;
  background: #2196f3;
  height: 40px;
  border-radius: 23px;
  width: 40px;
  text-align: center;
  display: flex;
  align-items: center;
  color: white;
  font-size: 12px;
  margin-right: 5px;
}

.avatar-title {
  padding-top: 7px;
}

.contact-picker {
  overflow: hidden;
  height: 100%;
  z-index: 999999;
  .select-list {
    position: absolute;
    top: 0px;
    background: white;
    width: 100%;
    z-index: 99999;
    height: 100%;
    padding-bottom: 20px;
  }

  .selected-list {
    position: absolute;
    top: 0px;
    background: white;
    width: 100%;
    z-index: 999999;
    height: 100%;

    .selected-edit {
      position: absolute;
      right: 10px;
    }

    .selected-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 24px;
      border-bottom: 1px solid #eeeeee;

      .avatar {
        justify-content: center;
        background: #2196f3;
        height: 40px;
        border-radius: 23px;
        width: 40px;
        text-align: center;
        display: flex;
        align-items: center;
        color: white;
        font-size: 12px;
        margin-right: 10px;
      }
    }

    .head {
      height: 45px;
      line-height: 45px;
      border-bottom: 1px solid #eee;

      p {
        text-align: center;
        color: #333;
      }

      span {
        text-align: right;
      }
    }
  }

  .sel {
    background: #F2F2F6;
    padding: 0px 15px;
    border-radius: 15px;
    margin: 15px;
    display: flex;
    align-items: center;

    input {
      background: #F2F2F6;
      border: none;
      height: 37px;
      line-height: 37px;
    }
  }

  .sel-list {
    overflow-y: auto !important;
    height: 100%;
    padding-bottom: 40px;
  }

  .list {
    margin-bottom: 40px;
    height: 80vh;
    overflow-y: auto !important;

    .avatar-title {
      padding-top: 7px;
    }
  }

  .nodata {
    text-align: center;
    font-size: 16px;
  }

  .navigation div {
    margin: 10px 0px;
    display: inline-block;
    padding: 0px 5px;
  }

  .level {
    color: #4397ff;
    padding-left: 16px!important;
  }

  .can-click {
    color: #4397ff;
    border-left: 1px solid #e2e2e2;
    padding-left: 10px;
  }

  .disabled {
    color: #cccccc;
    border-left: 1px solid #e2e2e2;
    padding-left: 10px;
  }

  .footer {
    background: #ffffff;
    border-top: 1px solid #cccccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    color: #4397ff;
    position: absolute;
    bottom: 0px;
    width: 100%;
    height: 40px;

    .btn {
      background: #4397ff;
      padding: 5px 10px;
      border-radius: 5px;
      color: #fff;
    }
  }
  .footer-cell {
    z-index: 99;
    background: #ffffff;
    border-top: 1px solid #cccccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    color: #4397ff;
    position: fixed;
    bottom: 0px;
    width: 100%;
    height: 40px;
    .btn {
      background: #4397ff;
      padding: 5px 10px;
      border-radius: 5px;
      color: #fff;
    }
  }
  .footer-cell-boot {
    z-index: 99;
    background: #ffffff;
    border-top: 1px solid #cccccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    color: #4397ff;
    // position: absolute;
    // bottom: -470px;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 40px;
    .btn {
      background: #4397ff;
      padding: 5px 10px;
      border-radius: 5px;
      color: #fff;
    }
  }
}
.closePicker {
  color: #4397ff;
  font-size: 13x;
  float: right;
  margin-right: 10px;
  margin-top: 10px;
}
</style>
